package nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import node.NodeImitator;

import com.renderbus.ep.SocketThread;

import entity.Node;
import entity.Task;

/**
 * NIO服务端
 * @author 小路
 */
public class NioRoot {
	
	public static Map<Integer,Node> nodeMap = new HashMap<Integer,Node>();
	public static Map<Integer,Task> taskMap = new HashMap<Integer,Task>();
	
	//通道管理器
	private Selector selector;
	public static String command = null;
	public static  Pipe commandNoticeNodes ;


	/**
	 * 获得一个ServerSocket通道，并对该通道做一些初始化的工作
	 * @param port  绑定的端口号
	 * @throws IOException
	 */
	public void initServer() throws IOException {
		int count = 100;
		//启动nodes服务线程
		for(int i = 0;i < count;i++){
			NodeImitator ni = new  NodeImitator("127.0.0.1", i+7000);
			ni.start();
		}
		//读取node信息
		for(int i = 0;i < count;i++){
			Node node = new Node();
			node.setId(i);
			node.setName("node" +  i);
			node.setStatus(1);
			node.setPort(i+7000);
			nodeMap.put(i, node);
		}
		//启动连接nodes服务
		this.selector = Selector.open();
		commandNoticeNodes = Pipe.open();
		Pipe.SourceChannel sourceChannel = commandNoticeNodes.source();
		sourceChannel.configureBlocking(false);
		sourceChannel.register(selector, SelectionKey.OP_READ);
		
		
		Iterator<Integer> nodeI = nodeMap.keySet().iterator();
		Node node = null;
		while(nodeI.hasNext()){
			node = nodeMap.get(nodeI.next());
			SocketChannel sc = SocketChannel.open();
			sc.configureBlocking(false);
			sc.connect(new InetSocketAddress("127.0.0.1",node.getPort()));
			sc.register(selector, SelectionKey.OP_CONNECT);
			node.setSc(sc);
		}
	}

	/**
	 * 采用轮询的方式监听selector上是否有需要处理的事件，如果有，则进行处理
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	public void start() throws IOException {
		// 轮询访问selector
		while (true) {
			//当注册的事件到达时，方法返回；否则,该方法会一直阻塞
			selector.select();
			// 获得selector中选中的项的迭代器，选中的项为注册的事件
			Iterator ite = this.selector.selectedKeys().iterator();
			while (ite.hasNext()) {
				SelectionKey key = (SelectionKey) ite.next();
				// 删除已选的key,以防重复处理
				ite.remove();
				// 客户端请求连接事件
				if (key.isConnectable()) {
					if(key.channel() instanceof SocketChannel){
						SocketChannel channel = (SocketChannel) key
								.channel();
						// 获得和客户端连接的通道
						// 如果正在连接，则完成连接  
		                if(channel.isConnectionPending()){  
		                    channel.finishConnect();  
		                }
						// 设置成非阻塞
						//channel.configureBlocking(false);
		
						//在这里可以给客户端发送信息哦
						//channel.write(ByteBuffer.wrap(new String("execute\r\n").getBytes()));
						//在和客户端连接成功之后，为了可以接收到客户端的信息，需要给通道设置读的权限。
						channel.register(this.selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
						// 获得了可读的事件
					}else{
//						Pipe.SourceChannel sourceChannel = (Pipe.SourceChannel) key
//						.channel();
//						ByteBuffer buf = ByteBuffer.allocate(512);
//						int bytesRead;
//						try {
//							bytesRead = sourceChannel.read(buf);
//							byte[] b = new byte[bytesRead];
//							buf.get(b, 0, bytesRead);
//							System.out.println("source" +  new String(b));
//						} catch (IOException e) {
//							e.printStackTrace();
//						}
						
					}
					
				} else if (key.isReadable()) {
					if(key.channel() instanceof SocketChannel){
						read(key);
					}else{
			            ByteBuffer buf = ByteBuffer.allocate(512);
						Pipe.SourceChannel sourceChannel = (Pipe.SourceChannel) key.channel();
						int bytesRead;
						try {
							bytesRead = sourceChannel.read(buf);
							buf.flip();
							System.out.println("bytesRead" +  bytesRead);
							byte[] b = new byte[bytesRead];
							buf.get(b);
							System.out.println("source" +  new String(b));
							nodeMap.get(1).getSc().write(ByteBuffer.wrap("execute\r\n".getBytes()));
							buf.clear();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				} else {
					if(command != null){
						System.out.println("----------" + command);
						execute(key);
					}
				}

			}
			command = null;

		}
	}
	
	public void execute(SelectionKey key)throws IOException{
		SocketChannel channel = (SocketChannel) key.channel();
		System.out.println("0000" + command);
		channel.write(ByteBuffer.wrap(command.getBytes()));
	}
	/**
	 * 处理读取客户端发来的信息 的事件
	 * @param key
	 * @throws IOException 
	 */
	public void read(SelectionKey key) throws IOException{
		
		SocketChannel channel = (SocketChannel) key.channel();
		// 创建读取的缓冲区
		ByteBuffer buffer = ByteBuffer.allocate(512);
		channel.read(buffer);
		byte[] data = buffer.array();
		String msg = new String(data).trim();
		System.out.println("服务端收到信息："+msg);
		if(msg.startsWith("execute")){
			String[] msgs = msg.split("\\|");
			nodeMap.get(Integer.parseInt(msgs[1])).setStatus(1);
			taskMap.get(Integer.parseInt(msgs[2])).getJobs().get(Integer.parseInt(msgs[3])).setStatus(2);
			Controller.notice();
		}
	}
	
	/**
	 * 启动服务端测试
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		new Thread(){
			public void run(){
				ServerSocket ss = null;
				try {
					ss = new  ServerSocket(8888);
					Socket s = null;
					while(true){
						s = ss.accept();
						new SocketThread(s).run();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}.start();
		new Controller().start();
		NioRoot server = new NioRoot();
		server.initServer();
		server.start();
		
	}

}
